package com.wuliu.system.service.app.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuliu.common.constant.OrderConstants;
import com.wuliu.common.exception.ServiceException;
import com.wuliu.common.utils.*;
import com.wuliu.system.domain.*;
import com.wuliu.common.core.domain.entity.SysAppletUser;
import com.wuliu.system.domain.bo.AddTrackBo;
import com.wuliu.system.domain.bo.CalcOrderFeeBo;
import com.wuliu.system.domain.dto.app.*;
import com.wuliu.system.domain.dto.applet.QryOrderFeeDto;
import com.wuliu.system.domain.vo.app.CountVo;
import com.wuliu.system.domain.vo.app.TspOrderVo;
import com.wuliu.system.mapper.TspOrderMapper;
import com.wuliu.system.mapper.TspOrderPreMapper;
import com.wuliu.system.service.*;
import com.wuliu.system.service.app.AppTspOrderService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author realue
 * @version 1.0
 * @date 2023-10-24 23:08
 */
@Service
public class AppTspOrderServiceImpl extends ServiceImpl<TspOrderMapper, TspOrder> implements AppTspOrderService {
    @Resource
    private TspOrderMapper tspOrderMapper;
    @Resource
    private IBasFilesService basFilesService;
    @Resource
    private ITspTrackService tspTrackService;
    @Resource
    private CommonService commonService;
    @Resource
    private ISysSmsRecordService sysSmsRecordService;
    @Resource
    private TspOrderPreMapper tspOrderPreMapper;

    /**
     * 图片收件
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean recOrderByImage(RecOrderByImageDto dto) {
        List<TspOrder> orders = new ArrayList<>();
        List<BasFiles> basFiles = new ArrayList<>();
        List<TspTrack> tracks = new ArrayList<>();
        //去掉重复的单号
        List<RecOrderByImageDto.OrderByImageItem> orderByImageItemList = dto.getOrderByImageItems().stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RecOrderByImageDto.OrderByImageItem::getOrderNo))), ArrayList::new
        ));
        //当前用户信息
        SysAppletUser user = SecurityUtils.getAppletUser();
        List<String> orderNos = orderByImageItemList.stream().map(RecOrderByImageDto.OrderByImageItem::getOrderNo).collect(Collectors.toList());
        //查询已存在的运单
        List<TspOrder> existsOrder = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .in(TspOrder::getOrderNo, orderNos));
        for (RecOrderByImageDto.OrderByImageItem item : orderByImageItemList) {
            if (existsOrder.stream().anyMatch(t -> t.getOrderNo().equals(item.getOrderNo()))) {
                continue;
            }
            String orderId = IdUtil.randomUUID();
            TspOrder tspOrder = new TspOrder();
            tspOrder.setId(orderId);
            tspOrder.setOrderNo(item.getOrderNo());
            tspOrder.setStatus(OrderConstants.ORDER_STATUS_1);
            tspOrder.setCreateTime(DateUtils.getNowDate());
            tspOrder.setCreateBy(user.getUserName());
            tspOrder.setSourceType(1);
            tspOrder.setSrcUserId(user.getUserId());
            tspOrder.setSrcUserName(user.getUserName());
            tspOrder.setSrcUserNo(user.getUserNo());
            tspOrder.setSrcDeptId(user.getDeptId());
            tspOrder.setSrcDeptName(user.getDeptName());
            tspOrder.setRecTime(DateUtils.getTime());
            tspOrder.setSysAccount(user.getSysAccount());
            orders.add(tspOrder);
            if (StringUtils.isNotEmpty(item.getPhotoUrl())) {
                basFiles.add(commonService.buildBasFile(orderId, item.getPhotoUrl(), OrderConstants.ORDER_STATUS_1, user.getSysAccount()));
            }
            AddTrackBo addTrackBo = AddTrackBo.builder().orderNo(tspOrder.getOrderNo()).orderId(orderId)
                    .opCode(OrderConstants.ORDER_STATUS_1).opLat(dto.getLat()).opLng(dto.getLng())
                    .opUserName(user.getUserName()).opUserTel(user.getMobile())
                    .deptName(user.getDeptName()).build();
            tracks.add(commonService.buildTspTrack(addTrackBo));
        }
        if (StringUtils.isNotEmpty(tracks)) {
            tspTrackService.saveBatch(tracks);
        }
        if (StringUtils.isNotEmpty(basFiles)) {
            basFilesService.saveBatch(basFiles);
        }
        return this.saveBatch(orders);
    }

    /**
     * 到件扫描
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean toPieceOrder(ToPieceOrderDto dto) {
        if (StringUtils.isEmpty(dto.getToPieceOrderItems())) {
            throw new ServiceException("请先添加运单列表");
        }
        SysAppletUser user = SecurityUtils.getAppletUser();
        List<String> orderNos = dto.getToPieceOrderItems().stream().map(ToPieceOrderDto.ToPieceOrderItem::getOrderNo).collect(Collectors.toList());
        List<TspOrder> orders = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .in(TspOrder::getOrderNo, orderNos));
        List<TspOrder> upOrders = new ArrayList<>();
        List<TspTrack> insTracks = new ArrayList<>();
        List<BasFiles> basFiles = new ArrayList<>();
        dto.getToPieceOrderItems().forEach(t -> {
            String[] orderId = {""};
            orders.stream().filter(k -> k.getOrderNo().equals(t.getOrderNo())).findFirst().ifPresent(one -> {
                orderId[0] = one.getId();
                TspOrder tspOrder = new TspOrder();
                tspOrder.setId(one.getId());
                tspOrder.setStatus(OrderConstants.ORDER_STATUS_5);
                tspOrder.setUpdateTime(DateUtils.getNowDate());
                tspOrder.setUpdateBy(user.getUserName());
                upOrders.add(tspOrder);
                if (StringUtils.isNotEmpty(t.getPhotoUrl())) {
                    basFiles.add(commonService.buildBasFile(one.getId(), t.getPhotoUrl(), OrderConstants.ORDER_STATUS_5, user.getSysAccount()));
                }
            });
            AddTrackBo addTrackBo = AddTrackBo.builder()
                    .opCode(OrderConstants.ORDER_STATUS_5).opLat(dto.getLat()).opLng(dto.getLng())
                    .orderNo(t.getOrderNo()).orderId(orderId[0])
                    .opUserName(user.getUserName()).opUserTel(user.getMobile())
                    .deptName(user.getDeptName()).prevDeptNo(t.getPrevDeptNo())
                    .prevDeptName(t.getPrevDeptName()).build();
            insTracks.add(commonService.buildTspTrack(addTrackBo));
        });
        if (StringUtils.isNotEmpty(basFiles)) {
            basFilesService.saveBatch(basFiles);
        }
        tspTrackService.saveBatch(insTracks);
        return this.updateBatchById(upOrders);
    }

    /**
     * 发件扫描
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendOrder(SendOrderDto dto) {
        if (StringUtils.isEmpty(dto.getSendOrderItems())) {
            throw new ServiceException("请先添加运单列表");
        }
        SysAppletUser user = SecurityUtils.getAppletUser();
        List<String> orderNos = dto.getSendOrderItems().stream().map(SendOrderDto.SendOrderItem::getOrderNo).collect(Collectors.toList());
        List<TspOrder> orders = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .in(TspOrder::getOrderNo, orderNos));
        List<TspOrder> upOrders = new ArrayList<>();
        List<TspTrack> insTracks = new ArrayList<>();
        List<BasFiles> basFiles = new ArrayList<>();
        dto.getSendOrderItems().forEach(t -> {
            String[] orderId = {""};
            orders.stream().filter(k -> k.getOrderNo().equals(t.getOrderNo())).findFirst().ifPresent(one -> {
                orderId[0] = one.getId();
                TspOrder tspOrder = new TspOrder();
                tspOrder.setId(one.getId());
                tspOrder.setStatus(OrderConstants.ORDER_STATUS_4);
                tspOrder.setUpdateTime(DateUtils.getNowDate());
                tspOrder.setUpdateBy(user.getUserName());
                upOrders.add(tspOrder);
                if (StringUtils.isNotEmpty(t.getPhotoUrl())) {
                    basFiles.add(commonService.buildBasFile(one.getId(), t.getPhotoUrl(), OrderConstants.ORDER_STATUS_4, user.getSysAccount()));
                }
            });
            AddTrackBo addTrackBo = AddTrackBo.builder().orderNo(t.getOrderNo()).orderId(orderId[0])
                    .opCode(OrderConstants.ORDER_STATUS_4).opLat(dto.getLat()).opLng(dto.getLng())
                    .opUserName(user.getUserName()).opUserTel(user.getMobile())
                    .deptName(user.getDeptName()).nextDeptNo(t.getNextDeptNo())
                    .nextDeptName(t.getNextDeptName()).build();
            insTracks.add(commonService.buildTspTrack(addTrackBo));
        });
        if (StringUtils.isNotEmpty(basFiles)) {
            basFilesService.saveBatch(basFiles);
        }
        tspTrackService.saveBatch(insTracks);
        return this.updateBatchById(upOrders);
    }

    /**
     * 收件/称重收件
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean recOrder(RecOrderDto dto) {
        if (StringUtils.isEmpty(dto.getRecOrderItems())) {
            throw new ServiceException("请先添加运单列表");
        }
        SysAppletUser user = SecurityUtils.getAppletUser();
        List<String> orderNos = dto.getRecOrderItems().stream().map(RecOrderDto.RecOrderItem::getOrderNo).collect(Collectors.toList());
        List<TspOrder> orders = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .in(TspOrder::getOrderNo, orderNos));
        List<TspOrder> upOrders = new ArrayList<>();
        List<TspTrack> insTracks = new ArrayList<>();
        List<BasFiles> basFiles = new ArrayList<>();
        dto.getRecOrderItems().forEach(t -> {
            String[] orderId = {""};
            orders.stream().filter(k -> k.getOrderNo().equals(t.getOrderNo())).findFirst().ifPresent(one -> {
                orderId[0] = one.getId();
                TspOrder tspOrder = new TspOrder();
                tspOrder.setId(one.getId());
                tspOrder.setStatus(OrderConstants.ORDER_STATUS_1);
                tspOrder.setUpdateTime(DateUtils.getNowDate());
                tspOrder.setUpdateBy(user.getUserName());
                tspOrder.setSrcUserId(user.getUserId());
                tspOrder.setSrcUserName(user.getUserName());
                tspOrder.setSrcUserNo(user.getUserNo());
                tspOrder.setSrcDeptId(user.getDeptId());
                tspOrder.setSrcDeptNo(user.getDeptNo());
                tspOrder.setSrcDeptName(user.getDeptName());
                tspOrder.setRecTime(DateUtils.getTime());
                //蓝牙称重重新计算运费
                if (t.getActWeight().compareTo(BigDecimal.ZERO) > 0) {
                    tspOrder.setActWeight(t.getActWeight());
                    CalcOrderFeeBo calcOrderFeeBo = new CalcOrderFeeBo();
                    calcOrderFeeBo.setSysAccount(user.getSysAccount());
                    calcOrderFeeBo.setSrcProvince(one.getSrcProvince());
                    calcOrderFeeBo.setSrcCity(one.getSrcCity());
                    calcOrderFeeBo.setDstProvince(one.getDstProvince());
                    calcOrderFeeBo.setDstCity(one.getDstCity());
                    calcOrderFeeBo.setWeight(tspOrder.getActWeight());
                    calcOrderFeeBo.setCargoCnt(one.getCargoCnt());
                    calcOrderFeeBo.setCargoType(one.getCargoType());
                    tspOrder.setFee(commonService.calcFee(calcOrderFeeBo));
                } else {
                    tspOrder.setWeight(one.getWeight());
                }
                upOrders.add(tspOrder);
                if (StringUtils.isNotEmpty(t.getPhotoUrl())) {
                    basFiles.add(commonService.buildBasFile(one.getId(), t.getPhotoUrl(), OrderConstants.ORDER_STATUS_1, user.getSysAccount()));
                }
            });
            AddTrackBo addTrackBo = AddTrackBo.builder().orderNo(t.getOrderNo()).orderId(orderId[0])
                    .opCode(OrderConstants.ORDER_STATUS_1).opLat(dto.getLat()).opLng(dto.getLng())
                    .opUserName(user.getUserName()).opUserTel(user.getMobile())
                    .deptName(user.getDeptName()).build();
            insTracks.add(commonService.buildTspTrack(addTrackBo));
        });
        if (StringUtils.isNotEmpty(basFiles)) {
            basFilesService.saveBatch(basFiles);
        }
        tspTrackService.saveBatch(insTracks);
        return this.updateBatchById(upOrders);
    }

    /**
     * 派件扫描
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean dispOrder(DispOrderDto dto) {
        if (StringUtils.isEmpty(dto.getDispItems())) {
            throw new ServiceException("请先添加运单列表");
        }
        SysAppletUser user = SecurityUtils.getAppletUser();
        List<String> orderNos = dto.getDispItems().stream().map(DispOrderDto.DispItem::getOrderNo).collect(Collectors.toList());
        List<TspOrder> orders = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .in(TspOrder::getOrderNo, orderNos));
        List<TspOrder> upOrders = new ArrayList<>();
        List<TspTrack> insTracks = new ArrayList<>();
        List<BasFiles> basFiles = new ArrayList<>();
        dto.getDispItems().forEach(t -> {
            String[] orderId = {""};
            orders.stream().filter(k -> k.getOrderNo().equals(t.getOrderNo())).findFirst().ifPresent(one -> {
                orderId[0] = one.getId();
                TspOrder tspOrder = new TspOrder();
                tspOrder.setId(one.getId());
                tspOrder.setStatus(OrderConstants.ORDER_STATUS_8);
                tspOrder.setUpdateTime(DateUtils.getNowDate());
                tspOrder.setUpdateBy(user.getUserName());
                tspOrder.setDstUserId(user.getUserId());
                tspOrder.setDstUserNo(user.getUserNo());
                tspOrder.setDstUserName(user.getUserName());
                tspOrder.setDstDetpId(user.getDeptId());
                tspOrder.setDstDeptNo(user.getDeptNo());
                tspOrder.setDstDeptName(user.getDeptName());
                tspOrder.setDispTime(DateUtils.getTime());
                upOrders.add(tspOrder);
                if (StringUtils.isNotEmpty(t.getPhotoUrl())) {
                    basFiles.add(commonService.buildBasFile(one.getId(), t.getPhotoUrl(), OrderConstants.ORDER_STATUS_8, user.getSysAccount()));
                }
            });
            AddTrackBo addTrackBo = AddTrackBo.builder().orderNo(t.getOrderNo()).orderId(orderId[0])
                    .opCode(OrderConstants.ORDER_STATUS_8).opLat(dto.getLat()).opLng(dto.getLng())
                    .opUserName(user.getUserName()).opUserTel(user.getMobile())
                    .deptName(user.getDeptName()).build();
            insTracks.add(commonService.buildTspTrack(addTrackBo));
        });
        if (StringUtils.isNotEmpty(basFiles)) {
            basFilesService.saveBatch(basFiles);
        }
        tspTrackService.saveBatch(insTracks);
        return this.updateBatchById(upOrders);
    }

    /**
     * 图片签收
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean signOrder(SignOrderDto dto) {
        if (StringUtils.isEmpty(dto.getSignOrderItems())) {
            throw new ServiceException("请先添加运单列表");
        }
        SysAppletUser user = SecurityUtils.getAppletUser();
        List<String> orderNos = dto.getSignOrderItems().stream().map(SignOrderDto.SignOrderItem::getOrderNo).collect(Collectors.toList());
        List<TspOrder> orders = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .in(TspOrder::getOrderNo, orderNos));
        List<TspOrder> upOrders = new ArrayList<>();
        List<TspTrack> insTracks = new ArrayList<>();
        List<BasFiles> basFiles = new ArrayList<>();
        dto.getSignOrderItems().forEach(t -> {
            String[] orderId = {""};
            orders.stream().filter(k -> k.getOrderNo().equals(t.getOrderNo())).findFirst().ifPresent(one -> {
                orderId[0] = one.getId();
                TspOrder tspOrder = new TspOrder();
                tspOrder.setId(one.getId());
                tspOrder.setStatus(OrderConstants.ORDER_STATUS_10);
                tspOrder.setSignTime(DateUtils.getTime());
                tspOrder.setUpdateTime(DateUtils.getNowDate());
                tspOrder.setUpdateBy(user.getUserName());
                upOrders.add(tspOrder);
                if (StringUtils.isNotEmpty(t.getPhotoUrl())) {
                    basFiles.add(commonService.buildBasFile(one.getId(), t.getPhotoUrl(), OrderConstants.ORDER_STATUS_10, user.getSysAccount()));
                }
                //发送签收短信
                if (one.getSendSignSms() == 1) {
                    //TODO 签收短信内容
                    String content = "";
                    sysSmsRecordService.addSms(one.getDstTel(), content, one.getSysAccount());
                }
            });
            AddTrackBo addTrackBo = AddTrackBo.builder().orderNo(t.getOrderNo()).orderId(orderId[0])
                    .opCode(OrderConstants.ORDER_STATUS_10).opLat(dto.getLat()).opLng(dto.getLng())
                    .opUserName(user.getUserName()).opUserTel(user.getMobile())
                    .deptName(user.getDeptName()).build();
            insTracks.add(commonService.buildTspTrack(addTrackBo));
        });
        if (StringUtils.isNotEmpty(basFiles)) {
            basFilesService.saveBatch(basFiles);
        }
        tspTrackService.saveBatch(insTracks);
        return this.updateBatchById(upOrders);
    }

    /**
     * app首页统计
     *
     * @return
     */
    @Override
    public CountVo orderCount() {
        CountVo countVo = new CountVo();
        String nowDate = DateUtils.getDate();
        SysAppletUser user = SecurityUtils.getAppletUser();
        long count = tspOrderPreMapper.selectCount(new LambdaQueryWrapper<TspOrderPre>()
                .eq(TspOrderPre::getSysAccount, user.getSysAccount())
                .eq(TspOrderPre::getGrabUserId, user.getUserId())
                .eq(TspOrderPre::getStatus, OrderConstants.ORDER_PRE_STATUS_1)
                .ge(TspOrderPre::getGrabTime, nowDate)
                .le(TspOrderPre::getGrabTime, nowDate + " 23:59:59"));
        countVo.setNoCollect(count);
        List<TspOrderPre> orderPres = tspOrderPreMapper.selectList(new LambdaQueryWrapper<TspOrderPre>()
                .eq(TspOrderPre::getSysAccount, user.getSysAccount())
                .eq(TspOrderPre::getGrabUserId, user.getUserId())
                .eq(TspOrderPre::getStatus, OrderConstants.ORDER_PRE_STATUS_2)
                .ge(TspOrderPre::getRecTime, nowDate)
                .le(TspOrderPre::getRecTime, nowDate + " 23:59:59"));
        countVo.setCollected((long) orderPres.size());
        countVo.setCollectWeight(orderPres.stream().map(TspOrderPre::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
        countVo.setCollectFee(orderPres.stream().map(TspOrderPre::getFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        countVo.setCollectCod(orderPres.stream().map(TspOrderPre::getCod).reduce(BigDecimal.ZERO, BigDecimal::add));
        count = tspOrderMapper.selectCount(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getUserId())
                .eq(TspOrder::getDstUserId, user.getUserId())
                .eq(TspOrder::getStatus, OrderConstants.ORDER_STATUS_8)
                .ge(TspOrder::getDispTime, nowDate)
                .le(TspOrder::getDispTime, nowDate + " 23:59:59"));
        countVo.setNoSign(count);
        List<TspOrder> orders = tspOrderMapper.selectList(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getUserId())
                .eq(TspOrder::getDstUserId, user.getUserId())
                .eq(TspOrder::getStatus, OrderConstants.ORDER_STATUS_10)
                .ge(TspOrder::getSignTime, nowDate)
                .le(TspOrder::getSignTime, nowDate + " 23:59:59"));
        countVo.setSigned((long) orders.size());
        countVo.setSignWeight(orders.stream().map(TspOrder::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
        countVo.setSignFee(orders.stream().filter(t -> t.getPaySide() == OrderConstants.ORDER_PAY_SIDE_2).map(TspOrder::getFee).reduce(BigDecimal.ZERO, BigDecimal::add));
        countVo.setSignCod(orders.stream().map(TspOrder::getCod).reduce(BigDecimal.ZERO, BigDecimal::add));
        return countVo;
    }

    /**
     * 电子录单、传统录单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createOrder(TspOrderDto dto) {
        SysAppletUser user = SecurityUtils.getAppletUser();
        TspOrder tspOrder = new TspOrder();
        BeanUtil.copyProperties(dto, tspOrder);
        tspOrder.setId(IdUtil.simpleUUID());
        tspOrder.setSysAccount(user.getSysAccount());
        tspOrder.setCreateTime(DateUtils.getNowDate());
        tspOrder.setStatus(OrderConstants.ORDER_STATUS_1);
        tspOrder.setSrcUserId(user.getUserId());
        tspOrder.setSrcUserNo(user.getUserNo());
        tspOrder.setSrcUserName(user.getUserName());
        tspOrder.setRecTime(DateUtils.getTime());
        tspOrder.setSrcDeptId(user.getDeptId());
        tspOrder.setSrcDeptNo(user.getDeptNo());
        tspOrder.setSrcDeptName(user.getDeptName());
        String address = dto.getSrcProvince() + dto.getSrcCity() + dto.getSrcDistrict() + dto.getSrcAddr();
        Map<String, String> map = TencentLocationUtil.geoCoderRev(address);
        if (null != map) {
            tspOrder.setSrcLng(MapUtils.getString(map, "lng"));
            tspOrder.setSrcLat(MapUtils.getString(map, "lat"));
        }
        address = dto.getDstProvince() + dto.getDstCity() + dto.getDstDistrict() + dto.getDstAddr();
        map = TencentLocationUtil.geoCoderRev(address);
        if (null != map) {
            tspOrder.setDstLng(MapUtils.getString(map, "lng"));
            tspOrder.setDstLat(MapUtils.getString(map, "lat"));
        }
        AddTrackBo addTrackBo = AddTrackBo.builder().orderNo(tspOrder.getOrderNo()).orderId(tspOrder.getId())
                .opCode(OrderConstants.ORDER_STATUS_1)
                .opUserName(user.getUserName()).opUserTel(user.getMobile())
                .deptName(user.getDeptName()).build();
        tspTrackService.insertTspTrack(commonService.buildTspTrack(addTrackBo));
        return tspOrderMapper.insertTspOrder(tspOrder) > 0;
    }

    /**
     * 编辑运单
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean editOrder(TspOrderDto dto) {
        if (StringUtils.isEmpty(dto.getId())) {
            throw new ServiceException("运单id不能为空");
        }
        TspOrder existsOrder = tspOrderMapper.selectOne(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getId, dto.getId()));
        if (null == existsOrder) {
            throw new ServiceException("运单不存在");
        }
        SysAppletUser user = SecurityUtils.getAppletUser();
        TspOrder tspOrder = new TspOrder();
        BeanUtil.copyProperties(dto, tspOrder);
        tspOrder.setUpdateTime(DateUtils.getNowDate());
        tspOrder.setUpdateBy(user.getUserName());
        String address = dto.getSrcProvince() + dto.getSrcCity() + dto.getSrcDistrict() + dto.getSrcAddr();
        Map<String, String> map = TencentLocationUtil.geoCoderRev(address);
        if (null != map) {
            tspOrder.setSrcLng(MapUtils.getString(map, "lng"));
            tspOrder.setSrcLat(MapUtils.getString(map, "lat"));
        }
        address = dto.getDstProvince() + dto.getDstCity() + dto.getDstDistrict() + dto.getDstAddr();
        map = TencentLocationUtil.geoCoderRev(address);
        if (null != map) {
            tspOrder.setDstLng(MapUtils.getString(map, "lng"));
            tspOrder.setDstLat(MapUtils.getString(map, "lat"));
        }
        return tspOrderMapper.updateById(tspOrder) > 0;
    }

    /**
     * 查询运单详情
     *
     * @param orderNo
     * @return
     */
    @Override
    public TspOrderVo getOrderInfo(String orderNo) {
        SysAppletUser user = SecurityUtils.getAppletUser();
        TspOrder tspOrder = tspOrderMapper.selectOne(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, user.getSysAccount())
                .eq(TspOrder::getOrderNo, orderNo));
        if (null == tspOrder) {
            throw new ServiceException("运单不存在");
        }
        TspOrderVo tspOrderVo = new TspOrderVo();
        BeanUtil.copyProperties(tspOrder, tspOrderVo);
        List<TspTrack> tracks = tspTrackService.list(new LambdaQueryWrapper<TspTrack>()
                .eq(TspTrack::getOrderNo, orderNo)
                .eq(TspTrack::getSysAccount, user.getSysAccount())
                .orderByAsc(TspTrack::getOpTime));
        if (StringUtils.isNotEmpty(tracks)) {
            List<TspOrderVo.TspTrack> tspTracks = tracks.stream().map(t -> {
                TspOrderVo.TspTrack tspTrack = new TspOrderVo.TspTrack();
                BeanUtil.copyProperties(t, tspTrack);
                return tspTrack;
            }).collect(Collectors.toList());
            tspOrderVo.setTrackList(tspTracks);
        }
        List<BasFiles> basFiles = basFilesService.list(new LambdaQueryWrapper<BasFiles>()
                .eq(BasFiles::getRelationId, tspOrder.getId()));
        if (StringUtils.isNotEmpty(basFiles)) {
            List<TspOrderVo.BasFiles> basFilesList = basFiles.stream().map(t -> {
                TspOrderVo.BasFiles files = new TspOrderVo.BasFiles();
                BeanUtil.copyProperties(t, files);
                return files;
            }).collect(Collectors.toList());
            tspOrderVo.setBasFiles(basFilesList);
        }
        return tspOrderVo;
    }
}
